﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Jumpton.SFA.Server.BusinessRule.MasterData;
using Jumpton.SFA.Server.BusinessRule.System;
using Jumpton.SFA.Server.Entity;
using Jumpton.SFA.Server.BusinessRule;
using Jumpton.SFA.Server.BusinessRule.InStoreDataMeasures;
using Jumpton.SFA.Server.BusinessRule.CallRoute;
using Jumpton.SFA.Entity;
using Jumpton.Persistent;

public partial class CallRoute_Visit_History_Detail : PageBase
{
    private decimal _visitID;
    private RouteManager manager = new RouteManager();


    protected void Page_Load(object sender, EventArgs e)
    {
        decimal.TryParse(Request.QueryString["visit"], out _visitID);
        if (_visitID == 0)
            return;

        if (!IsPostBack)
        {
            VISITS visit = manager.LoadVisits(_visitID);
            Person person = new PersonManager().Load(int.Parse(visit.personid.ToString()));
            CUSTOMERS customer = new CustomerManager().Load(visit.CUSTOMERID);
            //CustomerCallReview callReview = manager.LoadCallReview(_visitID);
            //DataTable callReview = manager.LoadCallReview(_visitID).BillDataTable;
            lblCustomer.Text = customer.NAME;
            try
            {
                DictionaryItems di = new DictionaryItemsManager().Load(decimal.Parse(customer.CUSTCLASSCODE));


                lblChannel.Text = di.Name;
            }
            catch { }
            lblUser.Text = person.Name;

            string starttime = BusinessLogic.GetDateTime(visit.STARTTIME.ToString());
            string endtime = BusinessLogic.GetDateTime(visit.STOPTIME.ToString());
            lblStart.Text = starttime;
            lblStop.Text = endtime;
            lblTimeSpan.Text = BusinessLogic.DateDiff(DateTime.Parse(endtime), DateTime.Parse(starttime));
            lblRemark.Text = visit.Note;
            lbl_latitude.Text = visit.LATITUDE.ToString();
            lbl_longitude.Text = visit.LONGITUDE.ToString();
            //绑定指标
            DataTable dt = MeasuresGroupItemDetailValueManager.GetMeasuresTransactionInfo(" AND V.ID='" + _visitID + "'");
            DataTable dtMeasure = dt.Clone();
            foreach (DataRow row in dt.Rows)
            {
                if (dtMeasure.Select("MEASURE_ID='" + row["MEASURE_ID"].ToString() + "'").Count() < 1)
                    dtMeasure.ImportRow(row);
            }
            rptMeasure.DataSource = dtMeasure;
            rptMeasure.DataBind();

            //CPR信息
            //DataTable dtCPR = new CPR_ConfigManager().GetCPR_ConfigTable(MyStateManager.DomainID).BillDataTable;
            //rptCPR.DataSource = dtCPR;
            //rptCPR.DataBind();

            //绑定照片类型
            ddlPhotoType.DataSource = new DictionaryItemsManager().GetItemList(DictionaryEnum.PhotoType, MyStateManager.DomainID);
            ddlPhotoType.DataTextField = "Name";
            ddlPhotoType.DataValueField = "Code";
            //ddlPhotoType.DataValueField = "dictionaryitemid";
            ddlPhotoType.DataBind();
            ddlPhotoType.Items.Insert(0, new ListItem("--所有--", ""));
            ddlPhotoType_SelectedIndexChanged(sender, e);

            //BindPromotion(visit);


            //绑定分销数据
            CPR_BRAND.VisitID = _visitID.ToString();
            CPR_BRAND.DomainID = MyStateManager.DomainID.ToString();

            //绑定寻店数据
            BindVisitSummaryInfo();
        }
    }

    private void BindVisitSummaryInfo()
    {
        VISITS_SUMMARY summary = new VisitSummaryManager().GetVisitSummaryByVisitId(_visitID.ToString());
        if (null != summary)
        {

            this.txtTastePeople.Value = summary.TASTE_PEOPLE_NO.ToString();
            this.txtBuyNo.Text = summary.BUY_NO.ToString();
            txtTaste.Value = summary.TASTE;
            txtTasteNoodleType.Text = summary.TASTE_NOODLE_TYPE;
            txtTasteNoodleNo.Value = summary.TASTE_NOODLE_NO.ToString();
            txtGiftName.Value = summary.GIFT_NAME;
            txtGiftNo.Value = summary.GIFT_NO.ToString();
            txtBagSalesNo.Value = summary.BAG_SALES_NO.ToString();
            txtContainerSalesNo.Value = summary.CONTAINER_SALES_NO.ToString();
            ViewState["SummaryId"] = summary.ID;
        }
    }

    public void BindPhotoByVisit()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        if (ddlPhotoType.SelectedValue != "")
        {
            sb.Append(" AND PHOTO_TYPE_ID='" + ddlPhotoType.SelectedValue + "' ");
        }
        PhotoManager pm = new PhotoManager();
        ObjectTable ot = pm.LoadImagesByVisitID(_visitID, sb.ToString());
        dlPhotos.DataSource = ot;
        dlPhotos.DataBind();

    }

    protected void Unnamed1_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        HtmlAnchor a = e.Item.FindControl("anchor") as HtmlAnchor;
        PHOTO drv = e.Item.DataItem as PHOTO;
        if (a != null)
        {

            System.Text.StringBuilder sb = new System.Text.StringBuilder("");
            sb.Append("javascript:window.showModalDialog('ReadPhoto.aspx?id=");
            sb.Append(drv.ID);
            sb.Append("','','dialogHeight:660px;dialogWidth:660px;left='+(screen.width-100)/2+',top='+(screen.height-100)/2+',center:yes;help:no;status:no;toolbar:no;')");
            a.HRef = sb.ToString();
        }
        var image = e.Item.FindControl("img") as System.Web.UI.WebControls.Image;
        image.ImageUrl = "../IMAGE.aspx?" + drv.ID;

    }


    protected void ddlPhotoType_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindPhotoByVisit();
    }

    protected void btnResearch_Click(object sender, EventArgs e)
    {
        //Response.Redirect("Visit_History_List.aspx" + "?" + Request.QueryString);
    }

    protected void rptMeasure_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            GridView gv = e.Item.FindControl("gvMeasureTransation") as GridView;
            string measureID = DataBinder.Eval(e.Item.DataItem, "MEASURE_ID").ToString();
            gv.DataSource = MeasuresGroupItemDetailValueManager.GetMeasuresTransactionInfo(" AND V.ID='" + _visitID + "' AND MI.ID='" + measureID + "'");
            //gv.RowDataBound += new GridViewRowEventHandler(gv_RowDataBound);
            gv.DataBind();

        }

    }

    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType != DataControlRowType.DataRow)
            return;
        DataRowView view = e.Row.DataItem as DataRowView;

        //如果是照片，则显示该照片
        if ((bool)view["ISPHOTO"] && "" != view["PHOTOID"].ToString())
        {
            //HtmlAnchor a = new HtmlAnchor();
            //view["INPUTTYPE"].ToString() == "6"
            //Image image = new Image();
            //image.BorderStyle = BorderStyle.Solid;
            //image.Height = new Unit(80, UnitType.Pixel);
            //image.Width = new Unit(80, UnitType.Pixel);
            //image.ImageUrl = "../IMAGE.aspx?" + view["PHOTOID"].ToString();

            System.Text.StringBuilder sb = new System.Text.StringBuilder("");
            sb.Append("javascript:window.showModalDialog('ReadPhoto.aspx?id=");
            sb.Append(view["PHOTOID"].ToString());
            sb.Append("','','dialogHeight:660px;dialogWidth:660px;left='+(screen.width-100)/2+',top='+(screen.height-100)/2+',center:yes;help:no;status:no;toolbar:no;')");

            e.Row.Cells[1].Text += "&nbsp;&nbsp;&nbsp;&nbsp;<a href=" + sb.ToString() + ">查看照片</a>";
        }
    }

    protected void rptCPR_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            GridView gv = e.Item.FindControl("gvCPR") as GridView;
            string tableName = DataBinder.Eval(e.Item.DataItem, "TABLENAME").ToString();
            gv.DataSource = new OrderLineManager().QueryCPR(tableName, _visitID);
            gv.DataBind();
        }
    }

    #region 绑定查询数据
    public void BindPromotion(VISITS v)
    {
        //string datetime = "";
        //try
        //{
        //    datetime=BusinessLogic.GetDateTime(v.LAST_UPDATE_TIME.ToString(), "yyyyMMddHHmmss", "yyyy-MM-dd");
        //}
        //catch {
        //    datetime = DateTime.Now.ToString("yyyy-MM-dd");
        //}
        //System.Text.StringBuilder sb = new System.Text.StringBuilder();
        //DataTable dt = new Jumpton.SFA.Server.BusinessRule.PromotionManager().GetPromationTable(v.DOMAINID.ToString(), datetime, datetime, " AND V.ID='" + v.ID + "'");
        //ViewState["dt"] = dt;
        //GridPager1.DataSource = dt;
        //GridPager1.GridView = gvPromotion;
        //GridPager1.BindData();
        //GridPager1.Visible = gvPromotion.Rows.Count > 0;

    }
    #endregion
    protected void btnSave_Click(object sender, EventArgs e)
    {

        //前台添加验证
        try
        {
            VisitSummaryManager manager = new VisitSummaryManager();
            VISITS_SUMMARY summary = new VISITS_SUMMARY();
            summary.VISIT_ID = _visitID.ToString();
            summary.TASTE_PEOPLE_NO = int.Parse(this.txtTastePeople.Value);
            summary.BUY_NO = int.Parse(this.txtBuyNo.Text);
            summary.TASTE = txtTaste.Value;
            summary.TASTE_NOODLE_TYPE = txtTasteNoodleType.Text;
            summary.TASTE_NOODLE_NO = int.Parse(txtTasteNoodleNo.Value);
            summary.GIFT_NAME = txtGiftName.Value;
            summary.GIFT_NO = int.Parse(txtGiftNo.Value);
            summary.BAG_SALES_NO = int.Parse(txtBagSalesNo.Value);
            summary.CONTAINER_SALES_NO = int.Parse(txtContainerSalesNo.Value);
            if (null == ViewState["SummaryId"])
            {
                //插入
                summary.ID = DateTime.Now.Ticks.ToString();
                summary.IDENTITY1 = summary.IDENTITY2 = summary.IDENTITY3 = summary.IDENTITY4 = summary.IDENTITY5 = summary.IDENTITY6 = "";
                if (manager.Save(summary))
                {
                    ViewState["SummaryId"] = summary.ID;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert(\"保存数据成功\");", true);
                }
            }
            else
            {

                //更新
                summary.ID = ViewState["SummaryId"].ToString();

                if (manager.Update(summary))
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert(\"更新数据成功\");", true);
                }
            }
        }
        catch (Exception ex)
        {


            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert(\"" + ex.Message + "\");", true);
        }



    }
}
